TOOLPREFIX ?= riscv64-unknown-elf-

CC      := $(TOOLPREFIX)gcc
AS      := $(TOOLPREFIX)gcc
LD      := $(TOOLPREFIX)ld
OBJCOPY := $(TOOLPREFIX)objcopy
OBJDUMP := $(TOOLPREFIX)objdump

CFLAGS  := -Wall -O2 -ggdb -ffreestanding -fno-builtin -nostdlib -mcmodel=medany
CFLAGS  += -Iinclude
LDFLAGS := -z max-page-size=4096 -T kernel/boot/kernel.ld
OBJS := \
  kernel/boot/entry.o \
  kernel/boot/main.o \
  kernel/boot/uart.o \
  kernel/boot/console.o \
  kernel/boot/printf.o \
  kernel/boot/start.o \
  kernel/mm/pmm.o \
  kernel/mm/vm.o \
  kernel/trap/kernelvec.o \
  kernel/trap/trap.o \
  kernel/trap/syscall.o \
  kernel/trap/sysproc.o \
  kernel/trap/sysfile.o \
  kernel/proc/spinlock.o \
  kernel/proc/proc.o \
  kernel/proc/swtch.o \
  kernel/proc/trampoline.o \
  kernel/proc/exec.o \
  kernel/file/bio.o \
  kernel/file/file.o \
  kernel/file/fs.o \
  kernel/file/sleeplock.o \
  kernel/file/virtio_disk.o \
  kernel/file/pipe.o \
  kernel/file/log.o \
  kernel/file/string.o \
  kernel/mm/kalloc.o 
 

all: kernel.elf

kernel/%.o: kernel/%.c
	$(CC) $(CFLAGS) -c -o $@ $<

kernel/boot/%.o: kernel/boot/%.S
	$(AS) $(CFLAGS) -c -o $@ $<

kernel/trap/%.o: kernel/trap/%.S
	$(AS) $(CFLAGS) -c -o $@ $<

kernel/proc/%.o: kernel/proc/%.S
	$(AS) $(CFLAGS) -c -o $@ $<

kernel.elf: $(OBJS) kernel/boot/kernel.ld
	$(LD) $(LDFLAGS) -o $@ $(OBJS)
	$(OBJDUMP) -S $@ > kernel.asm

run: kernel.elf
	qemu-system-riscv64 -machine virt -bios none -kernel kernel.elf -nographic -smp 1 -m 128M

clean:
	rm -f $(OBJS) kernel.elf kernel.asm

.PHONY: all run clean
